﻿public static class ListNodeExtensions
{
    public static IEnumerable<int> AsEnumerable(this ListNode listNode)
    {
        var current = listNode;
        for (; current != null;)
        {
            yield return current.val;
            current = current.next;
        }
    }
}

/// <summary>
/// https://leetcode-cn.com/problems/add-two-numbers/
/// </summary>
public class Solution
{
    public ListNode? AddTwoNumbers(ListNode l1, ListNode l2)
    {
        using var e1 = l1.AsEnumerable().GetEnumerator();
        using var e2 = l2.AsEnumerable().GetEnumerator();

        var result = new ListNode();
        var current = result;
        int lasting = 0;
        for (; ; )
        {
            bool can1 = e1.MoveNext();
            bool can2 = e2.MoveNext();
            if (!can1 && !can2)
                break;
            int v1 = can1 ? e1.Current : 0;
            int v2 = can2 ? e2.Current : 0;
            var val = v1 + v2 + lasting;
            lasting = val / 10;
            current = current.next = new ListNode(val % 10);
        }
        if (lasting != 0)
            current.next = new ListNode(lasting % 10);
        return result.next;
    }
}